// 创建用户的小仓库
import { defineStore } from "pinia";
import { reqLogin, reqUserInfo } from "@/api/user";
import type { loginForm,loginResponse } from "@/api/user/type";
import { UserState } from "./types/type";
import { GET_TOKEN,REMOVE_TOKEN } from "@/utils/token";

import { constanteRoute } from "@/router/router";
//选择式API
let useUserStore = defineStore("User", {
  // 小仓库，存储数据
  state: ():UserState => {
    return {
        token: GET_TOKEN(),
        menuRoutes: constanteRoute,  //仓库存储生成菜单需要的数组（路由）
        username:'',
        avatar:'',
    };
  },
  actions: {
    async userLogin(data:loginForm) {
        let result:loginResponse =await reqLogin(data)

        if(result.code == 200){
            // pinia仓库存储token，使用的是js对象;
            this.token = (result.data.token as string)
            // 本地存储
            localStorage.setItem("token",this.token)
            return "ok";
        }else{
            return Promise.reject(new Error(result.data.message))
        }
    },
    async userInfo(){
      let result = await reqUserInfo();
      if(result.code == 200){
        this.username = result.data.checkUser.username;
        this.avatar = result.data.checkUser.avatar;
        return 'ok';
      }else{
        return Promise.reject('获取用户信息失败');
      }
    },
    userLogout(){
      this.username = '';
      this.avatar = '';
      this.token = '';
      // localStorage.removeItem("token")
      REMOVE_TOKEN();
    }
  },
  getters: {},
});
export default useUserStore;
